package com.example.test.api.interceptor;

import com.example.test.core.service.RedisService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Logger;

/**
 * Created by Frank.Liu on 2016/7/4.
 */
public class TokenInterceptor implements HandlerInterceptor {
    private static final Logger log = Logger.getLogger("TokenInterceptor");
    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token = httpServletRequest.getHeader("token");
        JSONObject jsonObject = new JSONObject();
        Boolean flag = false;
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        ServletOutputStream servletOutputStream;
        try {
            servletOutputStream = httpServletResponse.getOutputStream();
            String url = httpServletRequest.getRequestURI();
            if ("/api/".equals(url) || "/api/swagger-ui.html".equals(url)) {
                flag = true;
            } else {
                if (!StringUtils.isEmpty(token)) {
                    if (redisService == null) {//解决service为null无法注入问题
                        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(httpServletRequest.getServletContext());
                        redisService = (RedisService) factory.getBean("redisService");
                    }
                    Object redisValue = redisService.getStr(token);
                    if (null != redisValue) {
                        flag = true;
                    } else {
                        jsonObject.put("result", false);
                        jsonObject.put("message", "用户认证信息已过期，请重新登录！");
                        jsonObject.put("type", "0");
                        servletOutputStream.write(jsonObject.toString().getBytes("UTF-8"));
                        flag = false;
                    }
                } else {
                    jsonObject.put("result", false);
                    jsonObject.put("message", "访问受限！");
                    jsonObject.put("type", "0");
                    servletOutputStream.write(jsonObject.toString().getBytes("UTF-8"));
                    flag = false;
                }
            }
        } catch (Exception e) {
            log.info(e.getMessage());
            return flag;
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
